package com.example.myapplication;

import static androidx.constraintlayout.widget.ConstraintLayoutStates.TAG;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.service.autofill.FillEventHistory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.BreakIterator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.transform.Result;

public class RateActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "Rate";
    private float dollarRate = 23f;
    private float euroRate = 34f;
    private float wonRate = 90f;
    TextView show;
    private Handler handler;
    Bundle bundle;
    HttpHolder holder;
    Timer timer;
    private TimerTask task;

    public RateActivity() throws IOException {
    }

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarRate = sharedPreferences.getFloat("dollar_rate",0.1f);
        euroRate = sharedPreferences.getFloat("euro_rate",0.2f);
        wonRate = sharedPreferences.getFloat("won_rate",123f);

        Log.i(TAG,"onCreate:get from sp dollarRate="+dollarRate);
        Log.i(TAG,"onCreate:get from sp euroRate="+euroRate);
        Log.i(TAG,"onCreate:get from sp wonRate="+wonRate);



        Thread t = new Thread(this);
        t.start();

     //  handler = new Handler() {
      //     @Override
       //    public void handleMessage(@NonNull Message msg) {
       //       if (msg.what == 5) {
          //    Bundle bdl = (Bundle) msg.obj;
           //         dollarRate = bdl.getFloat("web-dollar");
            //        euroRate = bdl.getFloat("web-euro");
              //      wonRate = bdl.getFloat("web-won");

            //  }
          //     super.handleMessage(msg);
         //   }

      // };


    }

    public void myclick(View btn) {
        EditText rmb = findViewById(R.id.rmb_imp);
        String str = rmb.getText().toString();
        Log.i(TAG, "myclick: ");
        float r = 0.0f;
        float i = Float.parseFloat(str);
        if (btn.getId() == R.id.btn_dollar) {
            r = i * 6.3049f;
        } else if (btn.getId() == R.id.btn_euro) {
            r = i * 25f;
        } else if (btn.getId() == R.id.btn_won) {
            r = i * 90f;
        }
        TextView result = findViewById(R.id.Result);
        result.setText("结果为" + r);
    }

    public void onClick(View btn) {

        Log.i(TAG, "open: config");
        Intent intent = new Intent(RateActivity.this, ConfigActivity.class);

        startActivityForResult(intent, 3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "onActivityResult:requestCode" + requestCode);
        Log.i(TAG, "onActivityResult:resultCode" + resultCode);
        if (requestCode == 3 && resultCode == 6) {
            Bundle bdl = data.getExtras();
            dollarRate = bdl.getFloat("key_dollar2");
            euroRate = bdl.getFloat("key_euro2");
            wonRate = bdl.getFloat("key_won2");

            Log.i(TAG, "onActivityResult:dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult:euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult:wonRate=" + wonRate);

            SharedPreferences sp = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_setting) {
            Log.i(TAG, "open: config");
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {
        Log.i(TAG,"run:running......");
        for(int i=1;i<=6;i++){
            try {
                Thread.sleep(3000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        Message msg = handler.obtainMessage(5,bundle);
     //   msg.obj = "hello from run()";
        handler.sendMessage(msg);
        Log.i(TAG,"run:sendMessage ok");


        URL url = null;
        try {
            url = new URL("https://www.usd-cny.com/icbc.htm");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            InputStream in = http.getInputStream();

            String html = inputStream2String(in);

            Log.i(TAG,"run:html=" +html);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/icbc.htm").get();
            String title = doc.title();
            Log.i(TAG,"run:title="+title);

           Elements tds = doc.getElementsByTag("td");
           for(Element td:tds){
                Log.i(TAG,"run:td="+td.text());
            }
            //body > section > div > div > article > table > tbody > tr:nth-child(5) > td:nth-child(4)
            Elements trs = doc.getElementsByTag("tr");
            for(Element tr:trs){
           //     Elements tds = tr.getElementsByTag("td");
                Log.i(TAG,"run:td.size="+tds.size());
                if(tds.size()>0){
                    String td1 = tds.get(0).text();
                    String td2 = tds.get(5).text();
                    Log.i(TAG,"run:"+td1+"==>"+td2);
                }
            }
            Element table = doc.selectFirst("table");
            Element td = table.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(4) > td:nth-child(3)");
            Log.i(TAG,"run:td="+td.text());
            Element table2 = doc.selectFirst("table2");
            Element td2 = table.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(15) > td:nth-child(3)");
            Log.i(TAG,"run:td="+td.text());
            Element table3 = doc.selectFirst("table3");
            Element td3 = table.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(22) > td:nth-child(3)");
            Log.i(TAG,"run:td="+td.text());



        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        for (; ; ){
            int rsz = in.read(buffer,0,buffer.length);
            if (rsz < 0 )
                break;
            out.append(buffer,0,rsz);


        }


        return out.toString();
    }
    public static class WhiteFragment extends Fragment {

        Handler handler = new Handler(){
            public void handleMessage(Message msg){
                switch(msg.what){
                    case 200:
                }
            }
        };

        private String url =
                "https://www.usd-cny.com/icbc.htm";
        HttpHolder holder = new HttpHolder(handler);

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                holder.post(url,"",200);
            }
        };
    }
    @Nullable

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.whitefragment,null);
    }
    @Override
    public void onStart() {
        super.onStart();
        timer.schedule(task,0,10000);
    }

    @Override
    public void onStop() {
        super.onStop();
        timer.cancel();
    }

    private static class HttpHolder {
        public HttpHolder(Handler handler) {

        }

        public void post(String url, String s, int i) {
        }
    }
}

